//noinspection JSUnresolvedFunction
var express = require('express');
var router = express.Router();
var config = require('../config');
var co = require('co');
var BlogPost = require('../domain/BlogPost');
var PageResult = require('../common/PageResult');


// 看什么时候搞一个spring 的 ioc
var blogPost = new BlogPost();
/**
 * 博客详情页
 */
router.get('/:id', function (req, res, next) {
    // 这里使用 co 和 promise 解决异步回调问题
    co(function*() {
        let result = yield blogPost.findByOldId([req.params.id]);
        if (result.length == 0) {
            result = yield blogPost.findOne(req.params.id);
        }
        res.render('show', {blogPost: result[0]});
    });
});
/**
 * 博客列表页
 */
router.get('/list/:pageNo', (req, res, next)=> {
    co(function*() {
        var pageResult = new PageResult(req.params.pageNo, req.params.pageSize ? req.params.pageSize : 10);
        let sql = `select * from blog_post b order by b.created_at desc limit ${pageResult.offset},${pageResult.pageSize}`;
        let countSql = "select count(id) as count from blog_post";

        let resultCount = yield blogPost.execute(countSql, []);
        let data = [];
        if (resultCount[0].count > 0) {
            data = yield  blogPost.execute(sql, []);
        }
        pageResult.init(resultCount[0].count, data, '/posts/list');

        res.render('list', {pageResult: pageResult});
    });
});

module.exports = router;
